package com.mmall.common;

import com.mmall.util.PropertiesUtil;
import redis.clients.jedis.*;
import redis.clients.util.Hashing;
import redis.clients.util.Sharded;

import java.util.List;

import static com.google.common.collect.Lists.newArrayList;

public class RedisShardedPool {
    private static ShardedJedisPool pool;//ShardedJedisPool连接池

    private static Integer MaxTotal = Integer.parseInt(PropertiesUtil.getProperty("redis.max.total", "20"));//最大连接数
    private static Integer Minidle = Integer.parseInt(PropertiesUtil.getProperty("redis.min.idle", "2"));//最小连空闲数量
    private static Integer Maxidle = Integer.parseInt(PropertiesUtil.getProperty("redis.max.idle", "10"));//最大连空闲数量

    private static Boolean testOnBorrow = Boolean.parseBoolean(PropertiesUtil.getProperty("redis.test.brrow", "true"));//在进行jedis连接操作的时候是否验证连接可用
    private static Boolean testOnReturn = Boolean.parseBoolean(PropertiesUtil.getProperty("redis.test.retrun", "true"));//在进行jedis返回操作的时候是否验证连接可用

    private static Integer Prot1 = Integer.parseInt(PropertiesUtil.getProperty("redis1.prot"));
    private static String Ip1 = PropertiesUtil.getProperty("redis1.ip");

    private static Integer Prot2 = Integer.parseInt(PropertiesUtil.getProperty("redis2.prot"));
    private static String Ip2 = PropertiesUtil.getProperty("redis2.ip");

    private static void initPool() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(MaxTotal);
        config.setMaxIdle(Maxidle);
        config.setMinIdle(Minidle);
        config.setTestOnBorrow(testOnBorrow);
        config.setTestOnReturn(testOnReturn);
        config.setBlockWhenExhausted(true);//连接阻塞时是否超时,true阻塞直到超时.false返回连接错误

        //ip 端口 超时时间 毫秒
        JedisShardInfo jedisShardInfo1 = new JedisShardInfo(Ip1, Prot1, 1000 * 2);

        JedisShardInfo jedisShardInfo2 = new JedisShardInfo(Ip2, Prot2, 1000 * 2);

        List<JedisShardInfo> jedisShardInfoList = newArrayList();
        jedisShardInfoList.add(jedisShardInfo1);
        jedisShardInfoList.add(jedisShardInfo2);

        pool = new ShardedJedisPool(config, jedisShardInfoList, Hashing.MURMUR_HASH, Sharded.DEFAULT_KEY_TAG_PATTERN);

    }

    static {
        initPool();
    }

    public static ShardedJedis getjedis() {
        return pool.getResource();
    }

    public static void returnBrokenResource(ShardedJedis jedis) {

        pool.returnBrokenResource(jedis);
    }

    public static void retrunResource(ShardedJedis jedis) {

        pool.returnResource(jedis);
    }





    public static void main(String[] args) {
        ShardedJedis jedis = pool.getResource();

        for(int i=0;i<10;i++){
            jedis.set("key"+i, "key"+i);
        }

        retrunResource(jedis);
       // pool.destroy();//临时调用 销毁连接池中所有连接
        System.out.println("程序运行结束");
    }
}


